﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using POCOS;
using DAL;
using GUI.Models;
using BLL;
using BLL.Interfaces;
using System.Linq.Expressions;
using System.IO;
using GUI.Models.ModelArt;
using GUI.Infrastructure;
using WebMatrix.WebData;
using GUI.Models.AdminModels;
using System.Threading;
using System.Data.Objects.DataClasses;
using System.Drawing;
using Newtonsoft.Json;


namespace GUI.Controllers
{
    public class ArticlesController :Controller
    {





        private AuteurContext db = new AuteurContext();


        private IArticlesServices _articleservices;
        private IAuteurServices _auteurServices;

        List<String> culture;
        public ArticlesController(IArticlesServices articlesServices)
        {
            this._articleservices = articlesServices;
           
        }

           #region DashBoard
        public ActionResult Dashboard(string id)
          {
              int authorid =Convert.ToInt32( IntExtensions.Decode(id));
              var ListArticle= _articleservices.GetArticle().Where(a => a.AuteurId == authorid).ToList();
              ViewBag.artNbr = ListArticle.Count();
              
            
            
            return View();
           }

          #endregion



        // GET: /Articles/


        public JsonResult GetAuthor(int Id)
        {
          
            var idAuthor = Convert.ToInt32(Id);
            var objAuthor = from x in db.Auteurs
                            where (x.Id == Id)
                            select (new AuteurModel
                            {
                                Id = x.Id,
                                Name = x.Name,
                                Lastname = x.Lastname,
                                Profil = x.Profil

                            });
            return Json(objAuthor, JsonRequestBehavior.AllowGet);
        }


        [Authorize]
       
        public ActionResult Index(string id)
        {
            string iddecodde = IntExtensions.Decode(id);
            Session["currentauthorId"] = iddecodde;
            Session["authorIdEncoded"] = IntExtensions.Encode(iddecodde);
            ViewBag.session = Session["authorIdEncoded"];
             var authoridDecoded = Convert.ToInt32(IntExtensions.Decode(id));
           var author= _articleservices.FindAuthor(authoridDecoded);
            AuteurModel model = new AuteurModel();
            model.Id = author.Id;
            model.Name = author.Name; model.Lastname = author.Lastname; model.Profil = author.Profil;
            model.Adressmail = author.Adressmail;
            ViewBag.idauth = Convert.ToInt32(Session["currentauthorId"]);
            ViewBag.author = model;
                 ViewBag.knockoutest = db.UserProfiles.ToList();
        

            return View();
        }
        //
        // GET: /Articles/Details/5
        // get author detail Id 
          [Authorize]
        public PartialViewResult AuthorDetail()
        {

            int authorid = Convert.ToInt32(Session["currentauthorId"]);
            var authors = db.Auteurs.Where(a => a.Id == authorid).FirstOrDefault();
            return PartialView("_AuthorDetail");
        }
      [Authorize]
        public ActionResult Details(string id)
        {
            ViewBag.id = id;
            int isdetailar = Convert.ToInt32(IntExtensions.Decode(id));
            var article = _articleservices.GetArticleById(isdetailar);
            ArticleModel model = new ArticleModel();

            model.Title = article.Title;
            model.CreationDate = article.CreationDate;
            model.UpdateDate = article.UpdateDate;
            model.IsActive = article.IsActive;
            model.Culture = article.Culture;
            model.ArticleContenent = article.ArticleContenent;
            ViewBag.themes = GetThemeid(isdetailar);
            //image url // ImageByte

            model.ImageUrl = article.UrlImage;
            model.ImageBytes = article.ImageBytes;

            model.ImageMedium = article.ImageMedium;
            model.ImageLittle = article.ImageLittle;


            //ViewBag
            if (article.ImageBytes != null)
            {
             ViewBag.imagebyte = System.Convert.ToBase64String(article.ImageBytes);
            }

            if (article.ImageMedium != null)
            {
                 ViewBag.ImageMedium = System.Convert.ToBase64String(article.ImageMedium);
            }
             
            if (article.ImageLittle != null)
            {
                 ViewBag.ImageLittle = System.Convert.ToBase64String(article.ImageLittle);
            }
           
         
          
            ViewBag.culture = article.Culture;
            ViewBag.isactif = article.IsActive;
            ViewBag.ArticleCotenent = article.ArticleContenent;
            ViewBag.idauthor = Session["authorIdEncoded"];

        
        

            return View(model);
        }
     [Authorize]

        public ActionResult DetailArticle(int id)
        {

            var article = _articleservices.GetArticleById(id);
            ArticleModelAdmin model = new ArticleModelAdmin();
            model.Id = article.Id;
            model.Title = article.Title;
            model.CreationDate = article.CreationDate;
            model.UpdateDate = article.UpdateDate;
            model.IsActive = article.IsActive;

            model.ArticleContenent = article.ArticleContenent;
            model.Themes = article.themes;

            //image url // ImageByte

            model.ImageUrl = article.UrlImage;
            model.ImageBytes = article.ImageBytes;

            //ViewBag
            ViewBag.imagebyte = article.ImageBytes;
            ViewBag.ImageUrl = article.UrlImage;


            return View(model);
        }

        //
        // GET: /Articles/Create
        [Authorize]
        public ActionResult Create(string set02568auId)
        {
            string IdAuhtor = IntExtensions.Decode(set02568auId);

            Session["idauthor"] = Convert.ToInt32(Session["currentauthorId"]);

            ArticleModel model = new ArticleModel();

            model.CreationDate = DateTime.Now;



            model.AuteurId =Convert.ToInt32(IdAuhtor);

            //list des cultures 


            ViewBag.session = set02568auId;
            ViewBag.CultureId = new SelectList(db.Articles, "Id", "Culture", model.Culture);

            //IEqualityComparer<Themes> themecomparer = new DistinctThem();
            //IEnumerable<Themes> y = db.Themes.ToList().Distinct(themecomparer);

            //List<Themes> th = new List<Themes>();
            //foreach (var item in y)
            //{
            //    Themes themitem = new Themes();
            //    themitem.Id = item.Id;
            //    themitem.Subjects = item.Subjects;
            //    th.Add(themitem);
            //}




            //ViewBag.Theme = th;


            ViewBag.ThemeList = GetThemeTo(null);

            return View(model);
        }





        //Temes
 
        public ActionResult GetThemesAutocomplete(string term)
        {
            //IEqualityComparer<Themes> themecomparer = new DistinctThem();
            //IEnumerable<Themes> result = db.Themes.ToList().Distinct(themecomparer);

            var syggestion = from s in db.Themes
                             select s.Subjects;

            var namelist = syggestion.Where(n => n.ToLower().StartsWith(term.ToLower()));
            return Json(namelist, JsonRequestBehavior.AllowGet);
        }








        

        #region jtable
     
        [HttpPost]
        public JsonResult ArticleList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                Thread.Sleep(200);
                int articlcount = _articleservices.GetArticleCount();
                var articles = _articleservices.GetArticles(jtStartIndex, jtPageSize, jtSorting);


                //_articleServices._articleServices
                int id = WebSecurity.CurrentUserId;


                var result = from x in articles
                             where (x.AuteurId == id)

                             select new ArticleModel
                             {
                                 Id = x.Id,
                                 Title = x.Title,
                                 CreationDate = x.CreationDate,
                                 ArticleContenent = x.ArticleContenent,

                             };

                List<ArticleModel> lm = new List<ArticleModel>();

                foreach (var item in result)
                {
                    ArticleModel m = new ArticleModel();
                    m.Id = item.Id;
                    m.Title = item.Title;
                    m.CreationDate = item.CreationDate;
                    m.ArticleContenent = item.ArticleContenent;
                    m.EncodeId = IntExtensions.Encode(item.Id.ToString());
                    lm.Add(m);
                }



                return Json(new { Result = "OK", Records = lm, TotalRecordCount = articlcount }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

         [Authorize]
        public JsonResult ArticleListByFiter(string date, int auteurid = 0, int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {




                var studentCount = _articleservices.GetArticleCountByFilter(date, auteurid);
                var articles = _articleservices.GetArticlesByFilter(date, auteurid, jtStartIndex, jtPageSize, jtSorting);

                //_articleServices._articleServices
                //_articleServices._articleServices
                int id = WebSecurity.CurrentUserId;
                var authId = Convert.ToInt32(Session["currentauthorId"]);

                var result = from x in articles
                             where (x.AuteurId == authId)

                             select new ArticleModel
                             {
                                 Id = x.Id,
                                 Title = x.Title,
                                 CreationDate = x.CreationDate,
                                 ArticleContenent = x.ArticleContenent,

                             };

                List<ArticleModel> lm = new List<ArticleModel>();

                foreach (var item in result)
                {
                    ArticleModel m = new ArticleModel();
                    m.Id = item.Id;
                    m.Title = item.Title;
                    m.CreationDate = item.CreationDate;
                    m.ArticleContenent = item.ArticleContenent;
                    m.EncodeId = IntExtensions.Encode(item.Id.ToString());
                    lm.Add(m);
                }


                return Json(new { Result = "OK", Records = lm, TotalRecordCount = studentCount });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }


        }
      [Authorize]
        [HttpPost]
        public JsonResult CreateArticle(Article article)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
                }


                _articleservices.CreateArticle(article);
                return Json(new { Result = "OK", Record = article });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }


        [HttpPost]



        [Authorize(Roles = "Author")]
        public JsonResult UpdateArticle(ArticleModel Model)
        {

            var article = _articleservices.GetArticleById(Model.Id);

            if (article == null)
            {
                return Json(new { Status = "Failed" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                article.Id = Model.Id;
                article.Title = Model.Title;
                article.CreationDate = Model.CreationDate;

                _articleservices.UpdateArticle(article);

                return Json(new { Result = "OK" });
            }
        }





          [Authorize(Roles = "Author")]
        public JsonResult DeleteArticle(ArticleModel Model)
        {

            _articleservices.DeleteArticle(Model.Id);
            return Json(new { Result = "OK" });


        }





        #endregion

          #region imagebitmap
          public Image Base64ToImage(string base64String)
          {
              // Convert Base64 String to byte[]
              byte[] imageBytes = Convert.FromBase64String(base64String);
              MemoryStream ms = new MemoryStream(imageBytes, 0,
                imageBytes.Length);

              // Convert byte[] to Image
              ms.Write(imageBytes, 0, imageBytes.Length);
              Image image = Image.FromStream(ms, true);
              return image;
          }

          #endregion

          #region  chosen

          public MultiSelectList GetTheme(int articleId)
        {

            IEqualityComparer<Themes> themecomparer = new DistinctThem();
            IEnumerable<Themes> y = db.Themes.ToList().Where(x => x.ArticleId == articleId).Distinct(themecomparer);




            var ThemeList = (from a in y
                             select (new MultiSelectThemeModel
                             {
                                 Id = a.Id,
                                 Title = a.Subjects

                             })).ToList();

            List<string> stringArra = new List<string>();

            foreach (var item in y)
            {
                Themes th = new Themes();
                th.Id = item.Id;
                stringArra.Add(th.Id.ToString());
            }


            return new MultiSelectList(ThemeList, "Id", "Title", stringArra);


        }
        public MultiSelectList GetThemeTo(List<string> selectedValues)
        {
            IEqualityComparer<Themes> themecomparer = new DistinctThem();
            IEnumerable<Themes> y = db.Themes.ToList().Distinct(themecomparer);
            var ThemeList = (from a in y
                             select (new MultiSelectThemeModel
                             {
                                 Id = a.Id,
                                 Title = a.Subjects

                             })).ToList();



            return new MultiSelectList(ThemeList, "Id", "Title", selectedValues);
        }
        [HttpPost]
        #endregion



        #region article management
        public ActionResult Create(ArticleModel ArticleModel, List<int> ThemeList, HttpPostedFileBase fileBigSize, HttpPostedFileBase fileMediumsize, HttpPostedFileBase fileLittlesize)
        {

            //int idauth = Convert.ToInt32(Session["idauthor"]);

            int userId = WebSecurity.CurrentUserId;
            ArticleModel.IsActive = false;
            ArticleModel.UpdateDate = DateTime.Now;
            ArticleModel.CreationDate = DateTime.Now;

            Article article = new Article();

            if (ModelState.IsValid)
            {

                if (fileBigSize != null)
                {
                    byte[] uploadFile1 = new byte[fileBigSize.InputStream.Length];
                    fileBigSize.InputStream.Read(uploadFile1, 0, uploadFile1.Length);
                    article.ImageBytes = uploadFile1;
                }

                if (fileMediumsize != null)
                {
                    byte[] uploadFile2 = new byte[fileMediumsize.InputStream.Length];
                    fileMediumsize.InputStream.Read(uploadFile2, 0, uploadFile2.Length);
                    article.ImageMedium = uploadFile2;
                }

                if (fileLittlesize != null)
                {
                    byte[] uploadFile3 = new byte[fileLittlesize.InputStream.Length];
                    fileLittlesize.InputStream.Read(uploadFile3, 0, uploadFile3.Length);
                    article.ImageLittle = uploadFile3;
                }

                article.CreationDate = DateTime.Now;
                article.UpdateDate = DateTime.Now;
                article.IsActive = false;

                article.ArticleContenent = ArticleModel.ArticleContenent;
                article.Culture = ArticleModel.Culture;
                //auth
                article.AuteurId =ArticleModel.AuteurId;


                //List Of Thema checkboxes check box  and chosen boxes
                if (ThemeList != null)
                {
                    IEnumerable<Themes> themeVarieties = from item in db.Themes
                                                         where ThemeList.Contains(item.Id)
                                                         select item;
                    article.themes = themeVarieties.ToList();
                }
                
                _articleservices.CreateArticle(article);
                ModelState.Clear();
                return RedirectToAction("Details", new { id = IntExtensions.Encode(article.Id.ToString()) });
            }

            return View(article);
        }



        [HttpGet]
        public ActionResult EditArticle(string id_article_to_edit)
        {
            string iddecodde = IntExtensions.Decode(id_article_to_edit);

            var article_to_edit = _articleservices.GetArticleById(Convert.ToInt32(iddecodde));
            //var article_to_edit = _articleservices.GetArticleById(id_article_to_edit);    


            if (article_to_edit == null)
            {
                ViewBag.error = "msg erro";
            }
            ArticleModel model = new ArticleModel();

            model.Id = article_to_edit.Id;
            model.Title = article_to_edit.Title;
            model.AuteurId = article_to_edit.AuteurId;
            model.ArticleContenent = article_to_edit.ArticleContenent;

            model.UpdateDate = DateTime.Now;
            model.CreationDate = article_to_edit.CreationDate;
            //image
            model.ImageBytes = article_to_edit.ImageBytes;
            model.ImageMedium = article_to_edit.ImageMedium;
            model.ImageLittle = article_to_edit.ImageLittle;

            Session["ImageBytes"] = model.ImageBytes;
            Session["ImageMedium"] = model.ImageMedium;
            Session["ImageLittle"] = model.ImageLittle;

            //list des themes 

            ViewBag.Themesl = GetTheme(article_to_edit.Id);
            ViewBag.authorid = Session["authorIdEncoded"];

            return View(model);
        }
        [HttpPost]
        public ActionResult EditArticle(ArticleModel model, List<int> ThemeList, HttpPostedFileBase fileBigSize, HttpPostedFileBase fileMediumsize, HttpPostedFileBase fileLittlesize)
        {

            Article Article = new Article();
            //big size
            if (fileBigSize == null)
            {
                byte[] uploadFile1 = Session["ImageBytes"] as Byte[];
                model.ImageBytes = uploadFile1;
                Article.ImageBytes = model.ImageBytes;
            }
            else
            {
                byte[] uploadFile1 = new byte[fileBigSize.InputStream.Length];
                fileBigSize.InputStream.Read(uploadFile1, 0, uploadFile1.Length);
                Article.ImageBytes = uploadFile1;
            }

            //medium size 
            if (fileMediumsize == null)
            {
                byte[] uploadFile2 = Session["ImageMedium"] as Byte[];

                model.ImageMedium = uploadFile2;
                Article.ImageMedium = model.ImageMedium;
            }
            else
            {

                byte[] uploadFile2 = new byte[fileMediumsize.InputStream.Length];
                fileMediumsize.InputStream.Read(uploadFile2, 0, uploadFile2.Length);
                Article.ImageMedium = uploadFile2;


            }

            //littel size
            if (fileLittlesize == null)
            {
                byte[] uploadFile3 = Session["ImageLittle"] as Byte[];

                model.ImageLittle = uploadFile3;
                Article.ImageLittle = model.ImageLittle;
            }
            else
            {
                byte[] uploadFile3 = new byte[fileLittlesize.InputStream.Length];
                fileLittlesize.InputStream.Read(uploadFile3, 0, uploadFile3.Length);
                Article.ImageLittle = uploadFile3;
            }


            Article.Id = model.Id;
            Article.Title = model.Title;
            Article.ArticleContenent = model.ArticleContenent;
            Article.AuteurId = WebSecurity.CurrentUserId;
            Article.CreationDate = DateTime.Now;
            Article.UpdateDate = DateTime.Now;


            if (ThemeList != null)
            {
                IEnumerable<Themes> themeVarieties = from item in db.Themes
                                                     where ThemeList.Contains(item.Id)
                                                     select item;
                Article.themes = themeVarieties.ToList();
            }


            _articleservices.UpdateArticle(Article);
            return RedirectToAction("Index", "Articles", new { id = IntExtensions.Encode(model.AuteurId.ToString()) });
        }


        public IEnumerable<Themes> GetThemeid(int articleid)
        {
            IEqualityComparer<Themes> themecomparer = new DistinctThem();


            IEnumerable<Themes> y = db.Themes.Where(x => x.ArticleId == articleid).ToList().Distinct(themecomparer);


            return y;
        }





        public IEnumerable<Themes> ThemeList(int id)
        {

            IEqualityComparer<Themes> themecomparer = new DistinctThem();


            IEnumerable<Themes> y = db.Themes.Where(x => x.ArticleId == id).ToList().Distinct(themecomparer);

            return y;
        }

        # endregion



        #region  theme for the grid
        [HttpPost]
        public JsonResult GetThemeList(int Id)
        {
            try
            {
                Thread.Sleep(200);

                IEqualityComparer<Themes> themecomparer = new DistinctThem();
                IEnumerable<Themes> themes = db.Themes.ToList().Where(x => x.ArticleId == Id).Distinct(themecomparer);

                return Json(new { Result = "OK", Records = themes });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }


        [HttpPost]
        public JsonResult DeleteThemes(int Id)
        {
            try
            {
                Thread.Sleep(50);
                var th = db.Themes.Find(Id);
                db.Themes.Remove(th);
                return Json(new { Result = "OK" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        public JsonResult Updatethemes(Themes themes)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
                }

                db.Entry(themes).State = EntityState.Modified;
                return Json(new { Result = "OK" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }
        #endregion



        #region aticles admin JQGrid
        //get theme by article id
        public JsonResult GetThemebyarticleId(int id)
        {
            var jsonData = (from a in db.Themes
                            where a.ArticleId == id
                            select new
                            {
                                Id = a.Id,
                                Subjects = a.Subjects
                            }).ToList();
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
                 

        [Authorize]
        public JsonResult GetListArticles(string sidx, string sord, int page, int rows)
        {
            Arad arad = new Arad();
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            var listType = _articleservices.GetArticle();
            var todolist = listType.Select(x => new Arad
            {

                Id = x.Id,
                Title = x.Title,
                IsActive = x.IsActive,
                AuteurId=x.AuteurId,
                DateCreation = x.CreationDate 
            });
                    

            int totalRecords = todolist.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if (sord.ToUpper() == "DESC")
            {
                todolist = todolist.OrderByDescending(s => s.DateCreation);
                todolist = todolist.Skip(pageIndex * pageSize).Take(pageSize);
            }
            else
            {
                todolist = todolist.OrderBy(s => s.DateCreation);
                todolist = todolist.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = todolist
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        
        
        //update article
        [HttpPost]
        public JsonResult Uparticlecontenent(ArticleDetail article)
              {
                  var art = db.Articles.Include("Auteur").FirstOrDefault(e => e.Id == article.Id);
                  Thread.Sleep(2000);
                  if (art != null)
                  {

                      Article model = new Article();
                      if (article != null)
                      {
                          art.ArticleContenent = article.ArticleContenent;
                          model.UpdateDate = DateTime.Now;
                          art.Title = article.Title;

                          db.SaveChanges();

                          return Json(new { status = "update done Successfully !" }, JsonRequestBehavior.AllowGet);
                      }
                  }
                  return Json(new { status = "update fail" }, JsonRequestBehavior.AllowGet);

              }

        //get articlebyid
        //subgrid
        [HttpGet]
        public JsonResult GetDetailsArticles(int id)
        {


            Thread.Sleep(3000);
            var jsonData = (from a in db.Articles
                            where a.Id == id
                            select new
                            {
                               Id=a.Id,
                               CreationDate = a.CreationDate,
                                ArticleContenent=a.ArticleContenent,
                                Tilte=a.Title,
                                AuthorId=a.AuteurId,
                               ImageBytes = a.ImageBytes,
                               ImageMedium=a.ImageMedium,
                               ImageLittle = a.ImageLittle
                            }
                               );

            var JsonObject = JsonConvert.SerializeObject(jsonData);
            return Json(JsonObject, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult tyni()
        {
            ArticleDetail arad = new ArticleDetail();

            return PartialView("/Views/Account/Partial/_Articleupdate.cshtml");
        }
    
        //format date display details under jqgrid
        public string formatdate(DateTime t)
        {
            if (t == null)
            {
                return String.Empty;

            }
            else


                return t.ToShortDateString();
        }
        [HttpPost]
        public JsonResult EditArticles(Arad objAM)
        {
            

            Article art = new Article();
            art.Id = objAM.Id;
            art.AuteurId = objAM.AuteurId;
            art.CreationDate = objAM.DateCreation;
            art.IsActive = objAM.IsActive;
            art.UpdateDate = DateTime.Now;





            var auteur = db.Auteurs.Find(objAM.AuteurId);

             Auteur author = new Auteur();

             auteur.Id = objAM.AuteurId;
             auteur.Name = objAM.NomAuteur;
             auteur.Lastname = objAM.PrenomAuteur;

        
            try
            {

                db.Entry(auteur).State = EntityState.Modified;
                db.SaveChanges();
                _articleservices.UpdateArticle(art);
              
              
                    return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
               
            }
            catch (Exception)
            {
                
                throw;
            }
            return Json(new { result = "ko" }, JsonRequestBehavior.AllowGet);


           
        }
        #endregion
    }
}




